const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

class MyPromise{
  constructor(exector){
    exector(this.resolve,this.reject);
  }
  //状态
  status = PENDING;
  value = undefined;
  reason = undefined;
  //成功回调存储
  successCallback= [];
  //失败回调存储
  failCallback = [];

  resolve=(value)=>{
    if(this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while(this.successCallback.length){
      this.successCallback.shift()(value);
    }
    // this.successCallback && this.successCallback(value);
  }

  reject=(reason)=>{
    if(this.status !==PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    // this.failCallback && this.failCallback(reason)
    while(this.failCallback.length){
      this.failCallback.shift()(reason);
    }
  }

  then=(successCallback,failCallback)=>{
    if(this.status === FULFILLED){
      successCallback(this.value)
    }else if(this.status === REJECTED){
      failCallback(this.reason)
    }else{
      //等待
      this.successCallback.push(successCallback);
      this.failCallback.push(failCallback);
    }
  }
}

module.exports = MyPromise;